<template>
  <div class="corp-container">
    <div class="upload-container">
      <upload @setImg="setImg"></upload>
      <!-- <upload1 @setImg="setImg"></upload1> -->
    </div>
    <div class="show-container">
      <img v-if="showImg" :src="showImg" alt="" />
    </div>
  </div>
</template>

<script>
import * as convert from '@/utils/fileConvert';
export default {
  name: 'corpImg',
  components: {
    upload: () => import('./comp/upload'),
    upload1: () => import('./comp/upload1')
  },
  data() {
    return {
      showImg: null
    };
  },
  methods: {
    setImg(imgObj) {
      let { file } = imgObj;
      this.processImage(file);
    },
    processImage(file, TARGET_SIZE = 88) {
      convert.fileToBase64(file).then(base64 => {
        const img = new Image();
        img.src = base64;
        img.onload = () => {
          // 创建画布
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          // 图片原始尺寸
          const { width, height } = img;
          // 计算缩放比例
          let scale;
          if (width > height) {
            scale = TARGET_SIZE / height;
          } else {
            scale = TARGET_SIZE / width;
          }
          // 将长度小的一边调整为 TARGET_SIZE,另外一边等比例缩放
          const newWidth = width * scale;
          const newHeight = height * scale;
          // 计算居中裁剪的坐标
          const x = (TARGET_SIZE - newWidth) / 2;
          const y = (TARGET_SIZE - newHeight) / 2;
          // 设置画布大小
          canvas.width = TARGET_SIZE;
          canvas.height = TARGET_SIZE;
          // 绘制图片
          ctx.drawImage(img, x, y, newWidth, newHeight);
          // 获取处理后的图片数据
          const processedImageSrc = canvas.toDataURL('image/png');
          this.showImg = processedImageSrc;
        };
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.corp-container {
  width: 100%;
  height: 100%;
  background-color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  overflow: hidden;

  .upload-container {
    margin: 0 20px;
    width: 200px;
    height: 200px;
    border: 1px solid #ddd;
  }

  .show-container {
    flex: 1;
    height: 100%;
    border-left: 1px solid #ddd;
    display: flex;
    overflow: auto;
    img {
      margin: auto;
    }
  }
}
</style>
